package com.bing;

import com.bing.handler.HelloWorldHandler;
import org.eclipse.jetty.security.ConstraintMapping;
import org.eclipse.jetty.security.ConstraintSecurityHandler;
import org.eclipse.jetty.security.HashLoginService;
import org.eclipse.jetty.security.LoginService;
import org.eclipse.jetty.security.authentication.BasicAuthenticator;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.util.security.Constraint;
import org.junit.Test;

/**
 * Created by kaibb on 15-9-4.
 */
public class HelloJetty {
    @Test
    public void testHelloJetty() throws Exception {
        Server server = new Server(8080);
        server.setHandler(new HelloWorldHandler());
        String zwlm = "中文乱码";
        System.out.println(zwlm);
        server.start();
        server.join();
    }

    /**
     * 静态文件服务
     */
    @Test
    public void testFileServer() throws Exception {
        //创建一个基本的jetty服务,并监听80端口.如果传入参数为0,则会分配一个随机端口,可在日志中看到.
        Server server = new Server(8080);

        ResourceHandler resourceHandler = new ResourceHandler();
        resourceHandler.setDirectoriesListed(true);
        resourceHandler.setResourceBase(".");
        resourceHandler.setWelcomeFiles(new String[]{"index.html"});

        server.setHandler(resourceHandler);
        server.start();
        server.join();
    }

    /**
     * Security Handler
     */
    @Test
    public void testSecurityHandler() throws Exception {
        Server server = new Server(8080);
        ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
        ConstraintMapping securityMapping =new ConstraintMapping();
        securityMapping.setPathSpec("/");
        Constraint constraint = new Constraint();
        constraint.setAuthenticate(true);
        constraint.setName("auth");
        constraint.setRoles(new String[]{"user", "admin"});

        securityMapping.setConstraint(constraint);

        securityHandler.addConstraintMapping(securityMapping);
        BasicAuthenticator basicAuthenticator =new BasicAuthenticator();
        securityHandler.setAuthenticator(basicAuthenticator);

        LoginService loginService = new HashLoginService("MyRealm","src/test/resources/realm.properties");

        securityHandler.setLoginService(loginService);
        server.setHandler(securityHandler);
        server.addBean(loginService);
        securityHandler.setHandler(new HelloWorldHandler());

        server.start();
        server.join();
    }

}
